﻿using System;
using System.Data;
using System.Data.Common;
using Oracle.ManagedDataAccess.Client;
using ZhCun.DbCore.BuildSQLText;

namespace ZhCun.DbCore.DBHelper
{
    public class OracleHelper : DbHelperBase
    {
        public OracleHelper(string connStr)
            : base(connStr)
        { }

        OracleConnection _DBConnectionObj;
        OracleCommand _DbCommandObj;
        OracleDataAdapter _DbDataAdapterObj;

        public override DbConnection DBConnectionObj
        {
            get
            {
                //SqlBulkCopy aa = new SqlBulkCopy(new SqlConnection());
                if (_DBConnectionObj == null)
                {
                    _DBConnectionObj = new OracleConnection(ConnStr);
                }
                return _DBConnectionObj;
            }
        }

        public override DbCommand DbCommandObj
        {
            get
            {
                if (_DbCommandObj == null)
                {
                    _DbCommandObj = new OracleCommand();
                    _DbCommandObj.BindByName = MyConfig.Oracle.BindByName;
                }
                return _DbCommandObj;
            }
        }

        protected internal override DbDataAdapter DbDataAdapterObj
        {
            get
            {
                if (_DbDataAdapterObj == null)
                {
                    _DbDataAdapterObj = new OracleDataAdapter();
                }
                return _DbDataAdapterObj;
            }
        }

        public override DbParameter CreateDbParameter(string paramName, object paramValue)
        {
            if (!MyConfig.Oracle.BindByName && paramName.Substring(0, 1) != BuildSQLBase.PARAMSIGN_ORACLE)
            {
                paramName = string.Format("{1}{0}", paramName, BuildSQLBase.PARAMSIGN_ORACLE);
            }
            return new OracleParameter(paramName, paramValue);
        }

        /// <summary>
        /// 批量拷贝插入
        /// </summary>
        public override int BulkInsert(DataTable dt)
        {
            throw new NotImplementedException("不支持 OracleBulkCopy 操作");
            //try
            //{
            //    //TODO: 使用 Oracle.ManagedDataAccess.Client  不支持 OracleBulkCopy 操作

            //    OracleBulkCopy bulkCopy = new OracleBulkCopy(_DBConnectionObj);
            //    bulkCopy.DestinationTableName = dt.TableName;
            //    bulkCopy.BatchSize = dt.Rows.Count;
            //    OpenConnection();
            //    bulkCopy.WriteToServer(dt);
            //}
            //catch (Exception ex)
            //{
            //    var dbEx = new DbHelperException("oracle BulkInsert 发生异常", this, ex);
            //    throw dbEx;
            //}
            //finally
            //{
            //    CloseConnect();
            //}
        }
    }
}